<?php

namespace app\common\model\mall\goods;

use think\Exception;
use think\Model;
use think\Db;

class Appraise extends Model
{
    // 表名
    protected $name = 'mall_goods_appraise';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'createtime';
    
    // 追加属性
    protected $append = [
        'user_id_text',
        "goods_id_text",
        'status_text',
        'url'
    ];

    protected static function init()
    {
        $config = get_addon_config('mall');
        self::afterUpdate(function ($row) use ($config) {
            if($row['goodsraty'] && $row['timeraty'] && $row['serviceraty']) {
                $totalScore = $row['goodsraty'] + $row['timeraty'] + $row['serviceraty'];
                //增加商品评分
                db("mall_goods_raty")->where("goods_id", $row["goods_id"])
                    ->inc("totalraty", $totalScore)->inc("goodsraty", $row['goodsraty'])
                    ->inc("serviceraty", $row['serviceraty'])->inc("timeraty", $row['timeraty'])
                    ->inc("users")->update();
                //增加商品评价数
                db('mall_goods_goods')->where('id', $row["goods_id"])->setInc('appraisenum');
                //将上述评价加入店铺评分
                db("mall_shop_raty")->where("shop_id", $row["shop_id"])
                    ->inc("totalraty", $totalScore)->inc("goodsraty", $row['goodsraty'])
                    ->inc("serviceraty", $row['serviceraty'])->inc("timeraty", $row['timeraty'])
                    ->inc("users")->update();

                // 查询该订单是否已经完成评价,修改order表中的isAppraise
                $ogRs = \app\common\model\mall\goods\Appraise::alias('ga')
                    ->join('__MALL_ORDER_GOODS__ og', 'ga.order_id=og.order_id and ga.goods_id=og.goods_id and ga.goodsspec_id=og.salespec_id', 'RIGHT')
                    ->where(['og.order_id' => $row['order_id'], "ga.goodsraty|ga.serviceraty|ga.timeraty" => 0])
                    ->field('og.id,ga.id gid')->select();
                if (empty($ogRs)) $isFinish = true;
                else $isFinish = false;
                //订单商品全部评价完则修改订单状态
                if ($isFinish) {
                    if (config("mall.isAppraiseScore") == 1) {
                        $appraiseScore = (int)config('mall.appraiseScore');
                        if ($appraiseScore > 0) {
                            //给用户增加积分
                            $dataRemarks = "评价订单【" . $row['orderNo'] . "】获得积分";
                            \app\common\model\User::score($appraiseScore, $row['user_id'], $dataRemarks);
                        }
                    }
                    //修改订单评价状态
                    db('mall_order_order')->where('id', $row['order_id'])->update(['appraiseis' => 1, 'closedis' => 1, 'status' => 'finished']);
                }
            }
        });
    }

    public function getUserIdTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['user_d']) ? $data['user_d'] : '');
        $name = "";
        if($value){
            $name = \app\common\model\User::where("id","=",$value)->field("nickname,username")->find();
            $name = $name["nickname"]!=""?$name["nickname"]:$name["username"];
        }
        return $name;
    }

    public function getUrlAttr($value, $data)
    {
        $value = $value ? $value : isset($data['goods_id'])?$data['goods_id']:"";
        return addon_url('mall/goods/detail', [':ids' => $value]);
    }

    public function getImageAttr($value, $data)
    {
        $value = $value ? $value : ($data['receivimg'] ? $data['receivimg'] : self::$config['default_goods_img']);
        return cdnurl($value);
    }

    public function getGoodsIdTextAttr($value, $data)
    {
        $value = $value ? $value : $data['goods_id'];
        $name = Db::name("mall_goods_goods")->getFieldById($value,"goodsname");
        return $name?mb_substr($name,0,20):"";
    }

    public function getStatusList()
    {
        return ['best' => __('Status best'),'good' => __('Status good'),'bad' => __('Status bad')];
    }     


    public function getStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 根据商品id获取各评价数
     */
    public function getGoodsEachApprNum($goodsId){
        $rs = $this->field('(goodsraty+timeraty+serviceraty) as sumScore')->where(['goods_id'=>$goodsId])->select();
        $data = [];
        $best=0;
        $good=0;
        $bad=0;
        foreach($rs as $k=>$v){
            $sumScore = $v['sumScore'];
            // 计算好、差评数
            if($sumScore >= 15*0.9){
                ++$best;
            }else if($sumScore < 15*0.6){
                ++$bad;
            }
        }
        $data['best'] = $best;
        $data['bad'] = $bad;
        $data['good'] = count($rs)-$best-$bad;
        // 晒图评价数
        $data['pic'] = $this->where(['receivimg'=>['<>',''],'goods_id'=>$goodsId])->count();
        // 总评价数
        $data['sum'] = $this->where(['goods_id'=>$goodsId])->count();
        return $data;
    }

}
